<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="经销商">
          <a-select
            v-model="storeIdAndChannelId"
            style="width: 100%"
            show-search
            optionFilterProp="children"
            :getPopupContainer="node => node.parentNode"
            @change="getAddressList"
          >
            v-if="addressList.length > '1'"
            <a-select-option v-for="(category,categoryIndex) in storeList" :key="categoryIndex.toString()"
                             :value="category.storeIdAndChannelId">
              {{ category.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="收货地址">
          <a-select
            v-model="address"
            style="width: 100%"
            :getPopupContainer="node => node.parentNode"
          >
            v-if="addressList.length > '1'"
            <a-select-option v-for="(category,categoryIndex) in addressList" :key="categoryIndex.toString()"
                             :value="category.id">
              {{ category.province }}{{ category.city }}{{ category.region }}{{ category.town }}{{ category.detailAddress }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol='labelCol'
          :wrapperCol='wrapperCol'
          label='备注：'>
          <a-input v-model="note" placeholder="请输入备注"/>
        </a-form-item>
        <a-button @click="handleAddProduct" type="primary" icon="plus">选择商品</a-button>
      </a-form>

      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
          selectedRowKeys2.length
        }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected2">清空</a>
      </div>
      <a-table
        style="height:300px"
        ref="table2"
        bordered
        size="middle"
        rowKey="id"
        :columns="columns2"
        :dataSource="dataSource2"
        :pagination="ipagination2"
        :loading="loading2"
        :rowSelection="{selectedRowKeys: selectedRowKeys2, onChange: onSelectChange2}"
        @change="handleTableChange2">
           <span slot="action" slot-scope="text, record">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete2(record)">
                  <a>删除</a>
                </a-popconfirm>
        </span>
        <span slot="productQuantity" slot-scope="text, record">
        <a-input placeholder="请输入数量" v-model="record.productQuantity"/>
        </span>
        <!-- <template v-for="col in ['productQuantity']" #[col]="{ text, record }">
           <a-input
             v-if="editable"
             :key="col"
             :value="text"
             style="margin: -5px 0"
             allow-clear
             @change="e => handleChange(e.target.value, record.key, col)"
           />
           <template v-else>
             {{ text }}
           </template>-->
        <!--</template>-->
      </a-table>
      <select-product-modal-channel ref="SelectProductModalChannel"
                                    @selectFinished="selectOK"></select-product-modal-channel>

    </a-spin>
  </a-modal>
</template>

<script>
import {getAction, postAction} from '@/api/manage'
import moment from 'moment'
import pick from 'lodash.pick'
import {FormTypes} from '@/utils/JEditableTableUtil'
import {JEditableTableMixin} from '@/mixins/JEditableTableMixin'
import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
import SelectProductModalChannel from './SelectProductModalChannel'

export default {
  components: {
    JMultiSelectTag,
    SelectProductModalChannel
  },
  name: 'OmsOrderModalJX',
  mixins: [JEditableTableMixin],
  data() {
    return {
      editEnable: true,
      selectedRowKeys2: [],
      selectionRows2: [],
      dataSource2: [],
      addressList: [],
      storeList: [],
      address: '',
      storeId: '',
      storeIdAndChannelId: '',
      channelId: '',
      note: '',
      editable: true,
      columns2: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'productName',
        },
        {
          title: '物料编码',
          align: 'center',
          dataIndex: 'productSkuCode'
        },
        {
          title: '商品单价',
          align: 'center',
          dataIndex: 'productPrice',
        },
        {
          title: '数量',
          align: 'center',
          dataIndex: 'productQuantity',
          scopedSlots: {customRender: 'productQuantity'}
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 200,
          scopedSlots: {customRender: 'action'}
        }
      ],
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      ipagination2: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      loading2: false,
      validatorRules: {
        memberId: {rules: [{required: true, message: '请输入memberId!'}]},
        receiverName: {rules: [{required: true, message: '请输入收货人姓名!'}]},
        receiverPhone: {rules: [{required: true, message: '请输入收货人电话!'}]},
        deleteStatus: {rules: [{required: true, message: '请输入删除状态：0->未删除；1->已删除!'}]},
      },
      url: {
        add: "/oms/omsOrder/addOmsOrder",
        edit: "/oms/omsOrder/edit",
        queryAddressList: '/ums/UmsMemberReceiveAddress/list',
        list: '/pms/pmsProduct/replenishmentOrderItem',
        storeList: '/stm/stmStoreInfo/getStoreAndChannel'
      }
    }
  },
  methods: {
    onClearSelected2() {
      this.selectedRowKeys2 = []
      this.selectionRows2 = []
    },
    handleDelete2(record) {
      console.log(record);
      console.log(this.dataSource2);
      const newData = this.dataSource2.filter(item => item.id !== record.id)
      this.dataSource2 = newData;
      console.log(this.dataSource2);
    },
    onSelectChange2(selectedRowKeys, selectionRows) {
      this.selectedRowKeys2 = selectedRowKeys
      this.selectionRows2 = selectionRows
    },
    handleTableChange2(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter2.column = sorter.field
        this.isorter2.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination2 = pagination
    },
    handleAddProduct() {
      if (this.storeIdAndChannelId == '') {
        this.$message.warning('请先选择经销商')
      } else {
        this.$refs.SelectProductModalChannel.show(this.storeIdAndChannelId);
      }

    },
    selectOK(data) {
      let params = {}
      params.storeId = this.storeId
      params.channelId = this.storeIdAndChannelId.split("-")[1];
      let userIds = "";
      for (var a = 0; a < data.length; a++) {
        userIds = userIds + "," + (data[a])
      }
      if (userIds.length > 1) {
        params.ids = userIds.substr(1);
      }
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          res.result.records.forEach(item => {
            item.productQuantity = ''
          })
          this.dataSource2 = res.result.records;
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleOk() {
      let params = {}
      params.storeId = this.storeId.substr(2)
      params.companyAddressId = this.address;
      params.omsOrderItemList = this.dataSource2;
      params.note = this.note;
      params.channelId = parseInt(this.storeIdAndChannelId.split("-")[1]);
      if(this.dataSource2==null || this.dataSource2.length==0){
        this.$message.warning("请选择商品");
        return;
      }
      postAction(this.url.add, params).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit("ok");
          this.visible = false;
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    getAddressList(id) {
      console.log(555)
      this.storeId = "0" + "-" + id.split("-")[0];
      this.address = '';
      this.addressList = [];
      this.dataSource2 = [];
      this.note = '';
      getAction(this.url.queryAddressList, {memberId: id.split("-")[0]}).then(res => {
        if (res.success) {
          this.addressList = res.result.records;
          console.log(this.addressList)
        } else {
          console.log(res.message)
        }
      })

    },
    show() {
      this.form.resetFields();
      this.address='';
      this.dataSource2 = [];
      this.storeIdAndChannelId = ''
      this.visible = true;
      getAction(this.url.storeList, {}).then((res) => {
        if (res.success) {
          this.storeList = res.result;
        } else {
          this.$message.warning(res.message)
        }
      })
    }
  }
}
</script>

<style scoped>
</style>